package org.xiong.disk.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import org.apache.avro.data.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.xiong.disk.bean.Msg;
import org.xiong.disk.bean.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;


@Component
public class DataInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前请求url
        StringBuffer requestURL = request.getRequestURL();
        String[] requestUrl = requestURL.toString().split("/");

        // 获取session中存储的用户对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");

        // 获取当前请求携带的path参数
        String path = request.getParameter("path");

        // 封装返回信息
        Msg msg = Msg.fail("禁止访问");
        String string = JSON.toJSONString(msg);

        if (path == null){
            if (!user.getPhone().equals(requestUrl[requestUrl.length-1])) {
                response.getWriter().write(string);
                response.getWriter().flush();
                return false;
            }
        }else{
            boolean contains = path.contains(requestUrl[requestUrl.length - 1]);
            if (  !(contains && user.getPhone().equals(requestUrl[requestUrl.length-1])) ){
                response.getWriter().write(string);
                response.getWriter().flush();
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
